package com.yiwenup.leetcode.daily;

import java.util.Arrays;

/**
 * https://leetcode-cn.com/problems/shortest-distance-to-a-character/
 **/
public class No0821 {
    /**
     * 执行用时：1 ms, 在所有 Java 提交中击败了98.08%的用户
     * 内存消耗：41.5 MB, 在所有 Java 提交中击败了14.73%的用户
     */
    public int[] shortestToChar(String s, char c) {
        int n = s.length();
        int[] res = new int[n];
        Arrays.fill(res, n + 1);

        int flag = -1;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == c) flag = i;
            if (flag != -1) res[i] = i - flag;
        }

        flag = -1;
        for (int i = n - 1; i >= 0; i--) {
            if (s.charAt(i) == c) flag = i;
            if (flag != -1) res[i] = Math.min(res[i], flag - i);
        }

        return res;
    }
}
